﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProjectManagement.Domain.Entities;
using ProjectManagement.Domain.Abstract;
using NHibernate;
using ProjectManagement.Domain.AutoMappings;
using NHibernate.Linq;

namespace ProjectManagement.Domain.Services
{
	public class UserService : IRepository<User>
	{
		private ISessionFactory factory = NHibernateHelper.CreateSessionFactory();
		public void Save(User entity)
		{
			using (var session = factory.OpenSession())
			{
				session.Save(entity);
			}
		}

		public void SaveOrUpdate(User user)
		{
			var session = factory.OpenSession();
			using (ITransaction trans = session.BeginTransaction())
			{
				session.SaveOrUpdate(user);
				trans.Commit();
			}
		}

		public void Remove(User entity)
		{
			using (var session = factory.OpenSession())
			{
				ITransaction trans = session.BeginTransaction();
				try
				{
					session.Delete(entity);
					trans.Commit();
				}
				catch (Exception)
				{
					trans.Rollback();
				}
				
			}
		}

		public void Update(User entity)
		{
			using (var session = factory.OpenSession())
			{
				using (ITransaction trans = session.BeginTransaction())
				{
					try
					{
						session.Update(entity);
						trans.Commit();
					}
					catch (Exception)
					{
						trans.Rollback();
					}
				}
				
			}
		}

		public IEnumerable<User> QueryAll()
		{
			using (var session = factory.OpenSession())
			{
				return session.QueryOver<User>().List();
			}
		}

		public User Get(int id)
		{
			using (var session = factory.OpenSession())
			{
				return session.Get<User>(id);
			}
		}

		public IEnumerable<User> ExitUser(string username, string password)
		{
			using (var session = factory.OpenSession())
			{
				return session.QueryOver<User>()
					.Where(u => u.UserName == username)
					.Where(u => u.Password == password)
					.List();
			}
		}

		public User GetUserByUserName(string username)
		{
			using(var session=factory.OpenSession())
			{
				return session.Query<User>()
					.Where(u => u.UserName == username)
					.FirstOrDefault();
			}
		}
		public IEnumerable<User> QueryUser(IEnumerable<User> source, string username,string realname)
		{
			return source
				.WhereIf(u => u.RealName.Contains(realname), string.IsNullOrEmpty(realname) == false)
				.WhereIf(u => u.UserName == username, string.IsNullOrEmpty(username) == false);
		}
		//检查用户名是否存在
		public bool CheckUserName(string username)
		{
			var usernames =new List<string>();
			foreach (var item in QueryAll())
			{
				usernames.Add(item.UserName);
			}
			if (usernames.Contains(username))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}
